package com.woniu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.mapper.BookMapper;
import com.woniu.pojo.Book;
import com.woniu.pojo.User;
import com.woniu.redis.RedisConst;
import com.woniu.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author YangChuanDong
* @description 针对表【t_book】的数据库操作Service实现
* @createDate 2024-12-06 16:58:08
*/
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService{
    @Autowired
    private BookMapper bookMapper;

    @Override
    // 先从缓存查找，如果找不到，再从数据库查找
    @Cacheable(cacheNames = "books",key = "#id")
    public Book findById(Integer id) {
        Book book = bookMapper.selectById(id);
        return book;
    }

    @Override
    public Book update(Book book) {
        return null;
    }

    @Override
    public void delete(Integer id) {

    }

    @Override
    public void deleteAll() {

    }

    /**
     * 分页查询所有图书，销量降序
     * 添加缓存
     * */
    @Override
    @Cacheable(cacheNames = "books",key = "#page")
    public List<Book> pageBook(Integer page,Integer size) {
        LambdaQueryWrapper<Book> bookLambdaQueryWrapper = new LambdaQueryWrapper<Book>()
                .orderByDesc(Book::getBuyCount);
        // 分页查询所有图书
        Page<Book> bookPage = new Page<>(page, size);
        List<Book> bookList = bookMapper.selectPage(bookPage, bookLambdaQueryWrapper).getRecords();
        return bookList;
    }

    /**
     * 缓存中初始化热销榜数据
     *
     * */
    @Override
    @Cacheable(cacheNames = "books",keyGenerator = "keyGenerator")
    public Page<Book> findTopSales(Integer firstPage, Integer pageSize) {
        LambdaQueryWrapper<Book> bookLambdaQueryWrapper = new LambdaQueryWrapper<Book>()
                .orderByDesc(Book::getBuyCount);
        // 分页查询所有图书
        Page<Book> bookPage = new Page<>(firstPage, pageSize);
        return bookMapper.selectPage(bookPage, bookLambdaQueryWrapper);
    }

    @Override
    @Cacheable(cacheNames = RedisConst.BOOK_DETAIL, key = "#root.methodName + ':' + #id")
    public Book findById(Long id) {
        return bookMapper.selectById(id);
    }

}




